package com.pancoit.bdsdkdemo.handler;

import android.os.Handler;
import android.util.Log;

import com.pancoit.bdsdkdemo.MainApp;
import com.pancoit.bdsdkdemo.constant.GlobalParams;
import com.pancoit.bdsdkdemo.constant.TerminalParams;
import com.pancoit.bdsdkdemo.entity.UserMessage;
import com.pancoit.bdsdkdemo.entity.dao.SessionDao;
import com.pancoit.bdsdkdemo.entity.dao.UserMessageDao;
import com.pancoit.bdsdkdemo.entity.emums.MessageStatusType;
import com.pancoit.bdsdkdemo.interfaces.IAgentListener;
import com.pancoit.bdsdkdemo.utils.PreferencesUtils;
import com.pancoit.bdsdkdemo.utils.Stringutil;
import com.pancoit.bdsdkdemo.utils.TimeUtil;
import com.pancoit.bdsdklibrary.constant.BeidouSDKParam;
import com.pancoit.bdsdklibrary.interfaces.I21ProtocolListener;
import com.pancoit.bdsdklibrary.manage.BeidouSDKManage;
import com.pancoit.bdsdklibrary.protocol.Protocal21Write;
import com.pancoit.bdsdklibrary.utils.FormatConversionUtil;

import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.sleep;

/**
 * - @Description:  北斗处理程序
 * - @Author:  LXJ
 * - @Time:  2019/11/14 11:20
 */
public class BeidouSDKHandler {
    private static BeidouSDKHandler mBeidouSDKHandler;
    private List<IAgentListener> mIAgentListenerList;
    //最后一条消息
    public static UserMessage lastMsg = null;

    public static BeidouSDKHandler getInstance() {
        if (mBeidouSDKHandler == null) {
            mBeidouSDKHandler = new BeidouSDKHandler();
        }
        return mBeidouSDKHandler;
    }

    /**
     * 初始化监听器
     */
    public void initializeListener() {
        mIAgentListenerList = new ArrayList<>();
        BeidouSDKManage.getInstance().setProtocolListener(mI21ProtocolListener);
    }

    /**
     * 添加监听器
     *
     * @param agentListener
     */
    public void addAgentListener(IAgentListener agentListener) {
        mIAgentListenerList.add(agentListener);
    }

    /**
     * 添加监听器
     *
     * @param agentListener
     */
    public void removeAgentListener(IAgentListener agentListener) {
        mIAgentListenerList.remove(agentListener);
    }

    /**
     * 状态倒计时，超过指定时间未收到终端回执则为失败
     */
    public void startSentStatusWaitSecTimer() {
        Handler delayHandler = new Handler();
        delayHandler.postDelayed(() -> {
            //本地数据库存储
            if (lastMsg == null) return;
            if (lastMsg.getStatus() == MessageStatusType.Unknown.getValue()) {
                lastMsg.setStatus(MessageStatusType.Faild.getValue());
                UserMessageDao.getInstance().update(lastMsg);
                lastMsg = null;
            }
        }, 10000);
    }

    /**
     * 获取中的信息
     */
    private void getTerminalInfo() {
        new Thread(() -> {
            try {
                if (TerminalParams.isConnectNormal) {//一代盒子
                    if (BeidouSDKParam.boxVersion == 1) {


                    } else {//二代盒子
                        int count = 0; // 连续获取20次，如果还是获取不到，那么这个设备可能无法获取蓝牙信息
                        while (TerminalParams.cardNumber.equals("") && count < 20 && TerminalParams.isConnectNormal) {
                            sleep(200);
                            BeidouSDKManage.getInstance().sendHexCommand(Protocal21Write.getInstance().CCPWD("2","000000"));
                            Log.e("登录",count+"");
                            count++;
                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                if (TerminalParams.isConnectNormal) {//一代盒子
                    if (BeidouSDKParam.boxVersion == 1) {


                    } else {//二代盒子
                        int count = 0; // 连续获取20次，如果还是获取不到，那么这个设备可能无法获取蓝牙信息
                        while (TerminalParams.cardNumber.equals("") && count < 20 && TerminalParams.isConnectNormal) {
                            sleep(300);
                            BeidouSDKManage.getInstance().sendHexCommand(Protocal21Write.getInstance().CCZDC(String.valueOf(GlobalParams.selfCheckingFrequency)));
                            sleep(300);
                            boolean isAutoConfig = PreferencesUtils.getBoolean(MainApp.getInstance(),GlobalParams.AUTO_CONNECT,false);
                            if (isAutoConfig){
                                String number = PreferencesUtils.getString(GlobalParams.AUTO_CONNECT_NUMBER);
                                //设置SOS信息
                                BeidouSDKManage.getInstance().sendHexCommand(Protocal21Write.getInstance().CCSHM("1", number, "300", "SOS"));
                                sleep(300);
                                //设置极限追踪
                                BeidouSDKManage.getInstance().sendHexCommand(Protocal21Write.getInstance().CCZZM("1", number, "70", "1"));
                                sleep(300);
                                //设置OK键信息
                                BeidouSDKManage.getInstance().sendHexCommand(Protocal21Write.getInstance().CCOKS("1", number, "我已安排到达"));
                                sleep(300);
                            }
                            //查询版本信息
                            BeidouSDKManage.getInstance().sendHexCommand(Protocal21Write.getInstance().CCVRQ());
                            Log.e("终端信息查询 - 参数设置",count+"");
                            count++;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /*******************************************(北斗2.1协议监听器)******************************************************/

    private I21ProtocolListener mI21ProtocolListener = new I21ProtocolListener() {
        @Override
        public void onConnectBleSuccess() {
            super.onConnectBleSuccess();
            TerminalParams.isConnectNormal = true;
            getTerminalInfo();
        }

        @Override
        public void onDisconnectBleSuccess() {
            super.onDisconnectBleSuccess();
            TerminalParams.isConnectNormal = false;
            Log.e("InfoMessage", "断开了连接");
            TerminalParams.initialize();
        }

        @Override
        public void onUnknownCommand(String var0) {
            super.onUnknownCommand(var0);
            Log.i("InfoMessage", "未知指令：" + var0);
        }

        @Override
        public void onAllCommandReceived(String var0) {
            super.onAllCommandReceived(var0);
            Log.i("InfoMessage", "onAllCommandReceived：" + var0);
            for (IAgentListener iAgentListener : mIAgentListenerList) {
                iAgentListener.onAllCommandPrint(var0);
            }
        }

        /**
         * 报文通信信息
         *
         * @param var0 十六进制指令
         *             var1[1] 信息类型
         *             var1[2] 发信方用户地址ID号
         *             var1[3] 报文形式：‘0’:汉字,‘1’:代码,‘2’:汉字和代码混合
         *             注：调用SDK里面的sendMessage默认返回的是'1'
         *             var1[4] 发信时间（UTC）,有问题，不推荐使用
         *             var1[5] 报文通信信息内容
         */
        @Override
        public void BDTXR(String var0, String[] var1) {
            Log.i("InfoMessage：接收到通信信息",FormatConversionUtil.hexToString(var0));
        }

        /**
         * 接收到混合模式报文信息
         * @param formNumber 发送者卡号
         * @param content 内容
         */
        @Override
        public void receivedMessage(String formNumber, String content) {
            super.receivedMessage(formNumber, content);
            String toNumber = TerminalParams.cardNumber;
            String time = TimeUtil.getNowTime();
            UserMessageDao.getInstance().save(formNumber, toNumber, time, content);
            SessionDao.getInstance().save(formNumber, time, content);
            for (IAgentListener iAgentListener : mIAgentListenerList) {
                iAgentListener.onMessageReceived(formNumber);
            }
        }

        /**
         * 终端信息输出
         *
         * @param var0 十六进制指令
         *             var1[1] 用户地址
         *             var1[2] 电池电量
         *             var1[3] 功率状况1
         *             var1[4] 功率状况2
         *             var1[5] 功率状况3
         *             var1[6] 功率状况4
         *             var1[7] 功率状况5
         *             var1[8] 功率状况6
         *             var1[9] 功率状况7
         *             var1[10] 功率状况8
         *             var1[11] 功率状况9
         *             var1[12] 功率状况10
         *             var1[13] 服务频度
         *             var1[14] IC卡等级
         *             var1[15] 通讯长度
         */
        @Override
        public void BDZDX(String var0, String[] var1) {
            Log.e("BDZDX", "终端信息：");
            super.BDZDX(var0, var1);
            TerminalParams.cardNumber = Stringutil.subStringNotZero(var1[1]);
            TerminalParams.electricity = Stringutil.subStringNotZero(var1[2]);
            TerminalParams.frequency = Integer.parseInt(var1[13]);
            TerminalParams.communicationLevel = var1[14];
            TerminalParams.beidouSignal1 = Integer.parseInt(var1[3]);
            TerminalParams.beidouSignal2 = Integer.parseInt(var1[4]);
            TerminalParams.beidouSignal3 = Integer.parseInt(var1[5]);
            TerminalParams.beidouSignal4 = Integer.parseInt(var1[6]);
            TerminalParams.beidouSignal5 = Integer.parseInt(var1[7]);
            TerminalParams.beidouSignal6 = Integer.parseInt(var1[8]);
            TerminalParams.beidouSignal7 = Integer.parseInt(var1[9]);
            TerminalParams.beidouSignal8 = Integer.parseInt(var1[10]);
            TerminalParams.beidouSignal9 = Integer.parseInt(var1[11]);
            TerminalParams.beidouSignal10 = Integer.parseInt(var1[12]);
        }

        /**
         * 发送状态反馈信息
         *
         * @param var0 十六进制指令
         *             var1[1] 相关语句标识符
         *             var1[2] 指令执行情况
         *             var1[3] 语句未正确响应的代码标识
         *             var1[4] 语句未正确响应原因的文字描述
         */
        @Override
        public void BDFKI(String var0, String[] var1) {
            super.BDFKI(var0, var1);
            switch (var1[2]) {
                case "Y":
                    //发送成功
                    MainApp.getInstance().showMsg("发送成功");
                    if (lastMsg != null) {
                        lastMsg.setStatus(MessageStatusType.Succeed.getValue());
                    }
                    break;
                case "N":
                    //发送成功
                    MainApp.getInstance().showMsg("发送失败");
                    if (lastMsg != null) {
                        lastMsg.setStatus(MessageStatusType.Faild.getValue());
                    }
                    break;
            }
            switch (var1[3]) {
                case "0":
                    //RDSS入站申请频度设置超出本机授权服务频度
                    MainApp.getInstance().showMsg("RDSS入站申请频度设置超出本机授权服务频度");
                    break;
                case "1":
                    //接收到系统的抑制指令，入站申请被抑制
                    MainApp.getInstance().showMsg("接收到系统的抑制指令，入站申请被抑制");
                    break;
                case "2":
                    //当前设置为无线电静默状态，入站申请被抑制
                    MainApp.getInstance().showMsg("当前设置为无线电静默状态，入站申请被抑制");
                    break;
                case "3":
                    //当前入站申请距离上次入站申请的时间间隔小于授权的服务频度
                    MainApp.getInstance().showMsg("当前入站申请距离上次入站申请的时间间隔小于授权的服务频度");
                    break;
            }

            //更新消息
            if (lastMsg != null) {
                UserMessageDao.getInstance().update(lastMsg);
                for (IAgentListener iAgentListener : mIAgentListenerList) {
                    iAgentListener.onCommandFeedback(lastMsg.getToNumber());
                }
                lastMsg = null;
            }
        }

        /**
         * SOS信息
         *
         * @param var0 十六进制指令
         *             var1[1]中心号码
         *             var1[2]频度
         *             var[3]发送内容
         */
        @Override
        public void BDHMX(String var0, String[] var1) {
            super.BDHMX(var0, var1);
            TerminalParams.sosCenterNumber = Stringutil.subStringNotZero(var1[1]);
            TerminalParams.sosFrequency = Integer.parseInt(var1[2]);
            TerminalParams.sosContent = var1[3];
            for (IAgentListener iAgentListener : mIAgentListenerList) {
                iAgentListener.onSOSInfoReceived(TerminalParams.sosCenterNumber, TerminalParams.sosFrequency, TerminalParams.sosContent);
            }
        }

        /**
         * 极限追踪模式设置/查询结果
         *
         * @param var0 十六进制指令
         *             var1[1] 中心号码
         *             var1[2] 频度
         *             var1[3] 模式 默认为正常模式
         *             1:正常模式，RD开RN开
         *             2:省电模式，RD开RN关
         *             3:定位模式，RD关RN开
         */
        @Override
        public void BDZZX(String var0, String[] var1) {
            super.BDZZX(var0, var1);
            TerminalParams.limitTrackingCenterNumber = Stringutil.subStringNotZero(var1[1]);
            TerminalParams.limitTrackingFrequency = Integer.parseInt(var1[2]);
            for (IAgentListener iAgentListener : mIAgentListenerList) {
                iAgentListener.onLimitTrackingInfoReceived(TerminalParams.limitTrackingCenterNumber, TerminalParams.limitTrackingFrequency);
            }
        }

        /**
         * OK设置/查询结果
         *
         * @param var0 十六进制指令
         *             var1[1] 中心号码
         *             var[2] 内容
         */
        @Override
        public void BDOKX(String var0, String[] var1) {
            super.BDOKX(var0, var1);
            TerminalParams.okCenterNumber = Stringutil.subStringNotZero(var1[1]);
            TerminalParams.okContent = var1[2];
            for (IAgentListener iAgentListener : mIAgentListenerList) {
                iAgentListener.onOKInfoReceived(TerminalParams.okCenterNumber, TerminalParams.okContent);
            }
        }

        /**
         * 版本信息
         *
         * @param var0 十六进制指令
         *             var1[1] 版本信息
         */
        @Override
        public void BDVRX(String var0, String[] var1) {
            super.BDVRX(var0, var1);
            TerminalParams.mcuVersion = var1[1];
            for (IAgentListener iAgentListener : mIAgentListenerList) {
                iAgentListener.onVersionInfoReceived(TerminalParams.mcuVersion);
            }
        }
    };
}
